package portal.monitor.controller;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import beans.HttpResultList;
import net.sf.json.JSONObject;
import portal.monitor.dao.MonitorSoftware;
import portal.monitor.dao.service.MonitorSoftwareService;
import portal.monitor.utils.MonBaseUtils;
import portal.monitor.utils.MonConfig;

@RestController
public class MonitorSoftwareServlet {
    @Autowired
    MonitorSoftwareService monitorSoftwareService;
    private HttpResultList result;
    @RequestMapping(value = "/MonitorSoftwareServlet", method = RequestMethod.POST)
    public void SoftwareService(HttpServletRequest request, HttpServletResponse response) throws IOException {
        result = new HttpResultList();
        String operateType = request.getParameter("operateType");
        try {
            switch (operateType) {
                case "add":
                    addSoftware(request);
                    break;
                case "delete":
                    deleteSoftware(request);
                    break;
                case "alter":
                    alterSoftware(request);
                    break;
                case "showAll":
                    showAll();
                    break;
                case "showPaged":
                    showPaged(request);
                    break;
                case "showDetail":
                    showDetail(request);
                    break;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST参数错误");
            response.getWriter().print(JSONObject.fromObject(result).toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST数字错误");
        }
        response.getWriter().print(JSONObject.fromObject(result).toString());
    }

    private void addSoftware(HttpServletRequest request) {
        String softwareName = request.getParameter("softwareName");
        String softwarePath = request.getParameter("softwarePath");
        MonitorSoftware monitorSoftware = new MonitorSoftware(softwareName, softwarePath);
        boolean res = monitorSoftwareService.insert(monitorSoftware) == 1;
        if(res){
        	createPLFile();
        }
        result.setResult(res);
    }

    private void deleteSoftware(HttpServletRequest request) {
        Integer softwareId = Integer.parseInt(request.getParameter("softwareId"));
        boolean res = monitorSoftwareService.deleteByPrimaryKey(softwareId) == 1;
        if(res){
        	createPLFile();
        }
        result.setResult(res);
    }

    private void alterSoftware(HttpServletRequest request) {
        Integer softwareId = Integer.parseInt(request.getParameter("softwareId"));
        String softwareName = request.getParameter("softwareName");
        String softwarePath = request.getParameter("softwarePath");
        MonitorSoftware monitorSoftware = new MonitorSoftware(softwareId, softwareName, softwarePath);
        boolean res = monitorSoftwareService.updateByPrimaryKey(monitorSoftware) == 1;
        if(res){
        	createPLFile();
        }
        result.setResult(res);
    }

    private void showAll() {
        List<MonitorSoftware> monitorSoftwareList = monitorSoftwareService.selectAll();
        List<Object> objects = new ArrayList<Object>(monitorSoftwareList);
        result.setResult(objects.size() > 0);
        result.setDatas(objects);
    }


    private void showPaged(HttpServletRequest request) {
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        List<MonitorSoftware> softwareList = monitorSoftwareService.selectByPage(currentPage, onePageCount);
        List<Object> objects = new ArrayList<Object>(softwareList);
        int pageNum = monitorSoftwareService.pageNum(onePageCount);
        result.setResult(objects.size() > 0);
        result.setMessage(pageNum + "");
        result.setDatas(objects);
    }

    private void showDetail(HttpServletRequest request) {
        Integer softwareId = Integer.parseInt(request.getParameter("softwareId"));
        MonitorSoftware monitorSoftware= monitorSoftwareService.selectByPrimaryKey(softwareId);
        List<Object> objects = new ArrayList<>();
        objects.add(monitorSoftware);
        result.setResult(monitorSoftware != null);
        result.setDatas(objects);
    }
    
    //当软件整体记录有变动时，更新PL文件
    private String createPLFile(){
    	
    	this.showAll();
    	List<Object> softwareObj = this.result.getDatas();
    	StringBuffer sb = new StringBuffer();
    	for(int i=0;i<softwareObj.size();i++){
    		MonitorSoftware ms = (MonitorSoftware) softwareObj.get(i);
    		String tmp = ms.getSoftwarePath();
    		tmp = tmp.substring(tmp.lastIndexOf("/")+1);
    		sb.append(tmp);
    		sb.append("\r\n");
    	}
    	File PLFile = new File(MonConfig.localBase+"/PL.txt");
    	if(PLFile.exists()){
    		PLFile.delete();
    	}
    	try {
			PLFile.createNewFile();
			MonBaseUtils.chmod(PLFile.getAbsolutePath());
			Writer out1 =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PLFile), "UTF-8"));
			out1.write(sb.toString());
	    out1.flush();
	    out1.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return null;
    }


}
